﻿using Bricks.Business.Models.Account;
using Bricks.Business.Service;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Bricks.Component.Utils;
using Bricks.Component.Utils.Extensions;
using Bricks.Site.Models.Purview;

namespace Bricks.Site.Web.Controllers
{
    /// <summary>
    /// 菜单管理
    /// </summary>
    [Export]
    public class MenuInfoController : BaseController
    {
        //[Import]
        //public IMenuInfoService MenuInfoService { get; set; }

        [Import]
        public IPurviewService PurviewService { get; set; }

        /// <summary>
        /// 菜单管理首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            //取得面板及工具栏信息
            ViewBag.PanelInfo = base.GetPanelInfo();
            ViewBag.ToolBarInfo = base.GetToolBarInfo();
            return View();
        }

        /// <summary>
        /// 获取数据列表/树表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetDataList()
        {
            var queryData = MenuInfoService.Menues.OrderBy(m => m.OrderNo).ToList();  //转换为List之后，可进行函数操作
            var data = from m in queryData
                       select new
                       {
                           iconCls = m.Icon,  //固定字段，作为treeField的图标
                           m.ID,
                           m.MenuName,
                           m.MenuCode,
                           m.Url,
                           m.MenuTypeNum,
                           MenuTypeString = GetMenuTypeString(m.MenuType),  //获取菜单类型的中文描述
                           m.Modal,
                           m.Width,
                           m.Height,
                           m.IsDeleted,
                           m.Description,
                           m.OrderNo,
                           m.PID
                       };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取权限菜单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPurviewMenuList()
        {
            var queryData = PurviewService.GetPurviewMenuList();
            var data = from m in queryData
                       select new
                       {
                           iconCls = m.Icon,  //固定字段，作为treeField的图标
                           m.ID,
                           m.MenuName,
                           m.MenuCode,
                           m.Url,
                           m.MenuTypeNum,
                           MenuTypeString = GetMenuTypeString(m.MenuType),  //获取菜单类型的中文描述
                           m.Modal,
                           m.Width,
                           m.Height,
                           m.IsDeleted,
                           m.Description,
                           m.OrderNo,
                           m.PID
                       };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 获取菜单类型的中文描述
        /// </summary>
        /// <param name="menuType"></param>
        /// <returns></returns>
        public string GetMenuTypeString(MenuType menuType)
        {
            string result = MenuType.Null.ToDescription();  //取得中文描述（扩展方法）
            switch (menuType)
            {

                case MenuType.Tab: result = MenuType.Tab.ToDescription(); break;
                case MenuType.Dialog: result = MenuType.Dialog.ToDescription(); break;
                case MenuType.Embed: result = MenuType.Embed.ToDescription(); break;
            }
            return result;
        }

        /// <summary>
        /// 新增或编辑
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Edit(string id, string pid)
        {
            MenuInfo model = new MenuInfo();
            //如果是编辑
            if (!String.IsNullOrEmpty(id))
            {
                Guid guidID = id.ToGuid();
                var record = MenuInfoService.Menues.FirstOrDefault(m => m.ID == guidID);
                if (record != null)
                {
                    model = record;
                    if (!model.PID.HasValue)
                        model.PID = Guid.Empty;
                }
            }
            //如果是新增
            else
            {
                //如果选中了节点，点新增，那么则将其父级设置为选中的节点
                if (!String.IsNullOrEmpty(pid))
                {
                    model.PID = Guid.Parse(pid);
                }
                else
                {
                    model.PID = Guid.Empty;
                }
                model.MenuTypeNum = 0;  //类型默认为空Null
            }
            return View(model);
        }

        /// <summary>
        /// 新增或编辑（响应）
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(MenuInfo model)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            var record = MenuInfoService.Menues.FirstOrDefault(m => m.ID == model.ID);

            //如果选择了无父级，那应该把PID置空
            if (model.PID.Equals(Guid.Empty))
                model.PID = null;
            //新增
            if (record == null)
            {
                result = MenuInfoService.Add(model);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //修改
            else
            {
                result = MenuInfoService.Modify(model);
                //if (result.ResultType == OperationResultType.Success)
                //    return View(result.AppendData);
            }
            //return View();
            return Json(result, "text/html");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Delete(string id)
        {
            Guid guidID = id.ToGuid();
            var exeResult = MenuInfoService.Delete(guidID);
            return Json(exeResult);
        }

        /// <summary>
        /// 排序设置
        /// </summary>
        /// <param name="id">ID</param>
        /// <param name="pid">PID</param>
        /// <param name="order">排序</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetOrder(string id, string pid, string order)
        {
            Guid guidID = id.ToGuid();
            Guid? guidPID = pid.ToGuid();
            if (guidPID.Equals(Guid.Empty))
                guidPID = null;

            var exeResult = MenuInfoService.SetOrder(guidID, guidPID, order);
            return Json(exeResult);
        }

        /// <summary>
        /// 获取下拉树（选择父级使用）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMenuComboTree()
        {
            var queryData = MenuInfoService.Menues.OrderBy(m => m.OrderNo).ToList();

            //添加无父级节点
            MenuInfo nullParent = new MenuInfo();
            nullParent.ID = Guid.Empty;
            nullParent.MenuName = "无父级";
            nullParent.PID = null;
            queryData.Insert(0, nullParent);  //插入到第一个

            var data = from m in queryData
                       select new
                       {
                           iconCls = "icon-application",  //固定字段，作为treeField的图标
                           id = m.ID,
                           text = m.MenuName,
                           parent = m.PID,
                       };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 设置禁用或启用
        /// </summary>
        /// <param name="id">记录ID</param>
        /// <param name="isEnable">是否启用</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetEnable(string id, string isEnable)
        {
            var result = new OperationResult(OperationResultType.NoChanged);
            Guid guidID = id.ToGuid();
            var record = MenuInfoService.Menues.FirstOrDefault(m => m.ID == guidID);
            if (record != null)
            {
                record.IsDeleted = isEnable == "False";
                //UserView view = new UserView();
                //view = record.CopyTo<UserView>();
                result = MenuInfoService.Modify(record);
                if (result.ResultType == OperationResultType.Success)
                    result.Message = (isEnable == "True" ? "启用" : "禁用") + "成功";
            }
            return Json(result);
            //return View();
        }

        /// <summary>
        /// 分配功能
        /// </summary>
        /// <returns></returns>
        public ActionResult Assign(string id)
        {
            ViewBag.MenuID = id;
            return View();
        }

        /// <summary>
        /// 分配功能（响应）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AssignPost(string menuID)
        {
            string data = Request.Form["Data"];
            List<MenuActionAssignView> list = JsonHelper.JsonDeserialize<List<MenuActionAssignView>>(data);
            OperationResult result = MenuInfoService.SaveAssign(menuID.ToGuid(), list);
            //OperationResult result = new OperationResult(OperationResultType.Success, "分配功能成功");
            return Json(result, "text/html");
        }

        /// <summary>
        /// 获取菜单功能列表
        /// </summary>
        /// <param name="id">地址上的菜单ID</param>
        /// <returns></returns>
        public ActionResult GetMenuActionList(string id)
        {
            var list = MenuInfoService.GetMenuActionList(id.ToGuid()).ToList();
            var data = from m in list
                       //select m;
                       select new MenuActionAssignView
                       {
                           ID = m.ID,
                           Icon = m.Icon,
                           ActionName = m.ActionName,
                           ActionCode = m.ActionCode,
                           ActionTypeNum = m.ActionTypeNum,
                           IsDeleted = m.IsDeleted,
                           Description = m.Description,
                           OrderNo = m.OrderNo,
                           ActionID = m.ActionID
                       };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 初始化功能类型下拉数据
        /// </summary>
        /// <returns></returns>
        public ActionResult InitActionTypeComboData()
        {
            List<ActionTypeClass> list = new List<ActionTypeClass>();
            list.Add(new ActionTypeClass() { ActionTypeNum = 0, ActionTypeString = "权限标识" });
            list.Add(new ActionTypeClass() { ActionTypeNum = 1, ActionTypeString = "功能按钮" });
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 引入现有功能
        /// </summary>
        /// <returns></returns>
        public ActionResult Import()
        {
            return View();
        }

        /// <summary>
        /// 引入现有功能（Post）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ImportPost()
        {
            //return View();

            OperationResult result = new OperationResult(OperationResultType.Success, "成功");
            return Json(result, "text/html");
        }

        /// <summary>
        /// 功能类型类
        /// </summary>
        public class ActionTypeClass
        {
            public int ActionTypeNum { get; set; }

            public string ActionTypeString { get; set; }
        }

        /// <summary>
        /// 获取菜单（用于搜索）
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult GetMenuForSearch(string pid)
        {
            var list = MenuInfoService.Menues;
            //如果传入了PID，则获取模块下的菜单列表
            if (!String.IsNullOrEmpty(pid))
            {
                Guid guPID = pid.ToGuid();
                list = list.Where(m => m.PID == guPID).OrderBy(m => m.OrderNo);
            }
            //如果没有传入PID，则获取模块列表（即顶级菜单）
            else
            {
                list = list.Where(m => m.PID == null || m.PID == Guid.Empty).OrderBy(m => m.OrderNo);
            }
            return Json(list, JsonRequestBehavior.AllowGet);
        }
    }
}
